package com.xdb.jdbc;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Properties;

import com.xdb.engine.impl.XDBEngineOnSQL1999Impl;
import com.xdb.exception.XDBRuntimeException;
import com.xdb.logging.LogFactory;
import com.xdb.logging.Logger;
import com.xdb.presistence.kv.XDBPresistenceOnKV;

/**
 * XDB数据库驱动
 * @author woate
 *
 */
public final class XDBDriver implements Driver {
	
	private static final Driver INSTANCE = new XDBDriver();
	/**
	 * XDB JDBC URL
	 */
	public static final String XDB_JDBC_URL = "jdbc:xdb/tdd";
	
	private static volatile boolean registered;
	static Logger logger;
	
	static{
		logger = LogFactory.getLog(XDBDriver.class);
		load();
	}
	
	static synchronized Driver load() {
		try {
			if (!registered) {
				logger.debug("开始向DriverManager注册XDB");
				registered = true;
				DriverManager.registerDriver(INSTANCE);
			}
		} catch (SQLException e) {
			logger.debug("向DriverManager注册XDB错误", e);
			throw new XDBRuntimeException(e);
		}
		return INSTANCE;
	}

	@Override
	public boolean acceptsURL(String url) throws SQLException {
		//校验JDBC连接串为jdbc:xdb:开始的都是有效的
		if(url.equals(XDB_JDBC_URL)){
			logger.debug("接受的JDBC连接串");
			return true;
		}else{
			logger.debug("不接受的JDBC连接串");
			return false;
		}
	}

	@Override
	public Connection connect(String url, Properties info) throws SQLException {
		try {
			if (info == null) {
				info = new Properties();
			}
			if (!acceptsURL(url)) {
				return null;
			}
			//根据连接串创建出XDBEngine
			//TODO 创建出JDBC
			return new XDBConnection(new XDBEngineOnSQL1999Impl(new XDBPresistenceOnKV()));
		} catch (Exception e) {
			//TODO
			return null;
		}
	}

	@Override
	public int getMajorVersion() {
		return 1;
	}

	@Override
	public int getMinorVersion() {
		return 1;
	}

	@Override
	public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
		//简单实现
		return new DriverPropertyInfo[0];
	}

	@Override
	public boolean jdbcCompliant() {
		return true;
	}
	@Deprecated
	@Override
	public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
		return null;
	}

}
